var mysql = require('mysql');
const sqlConnection = function(queryCb) {
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root',
        database: 'app'
    });
    connection.connect();
    queryCb(connection)
    connection.end();
}


const doQuery = function (username, succ, fail) {
    return sqlConnection(function(connection) {
        var sql = `SELECT * FROM USER WHERE username='${username}'`;
        connection.query(sql, function (err, result) {
            if (err) {
                fail(err)
                return;
            }
            succ(result)
        });
    })
}


const doInsert = function (data, succ,fail) {
    return sqlConnection(function(connection) {
        var addSql = 'INSERT INTO USER(Id,username,password) VALUES(0,?,?)';
        var addSqlParams = [data.username, data.password];
        connection.query(addSql, addSqlParams, function (err, result) {
            if (err) {
                fail(err)
                return;
            }
            succ(result)
        });
        
    })
}

const doUpdate = function (data, succ,fail) {
    return sqlConnection(function(connection) {
        var modSql = 'UPDATE USER SET name = ?,url = ?,alexa = ?,country = ? WHERE id = ?';
        // var modSqlParams = ['菜鸟移动站', 'https://m.runoob.com', 6];
        var modSqlParams = [data.name, data.url, data.alexa, data.country, data.id];
        //改
        connection.query(modSql, modSqlParams, function (err, result) {
            if (err) {
                console.log('[UPDATE ERROR] - ', err.message);
                fail(err)
                return;
            }
            succ(result)
            console.log('--------------------------UPDATE----------------------------');
            console.log('UPDATE affectedRows', result.affectedRows);
            console.log('-----------------------------------------------------------------\n\n');
        });
    })
    
}



module.exports = {
    doQuery,
    doUpdate,
    doInsert
}